package com.lvtongka.app.base

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.lvtongka.app.dialog.LoadingDialog


abstract class BaseNoFragment<T : ViewBinding, VM : BaseViewModel> : Fragment() {
    lateinit var binding: T
    lateinit var viewModel: VM
    // 加载框
    private var loadingDialog: LoadingDialog? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewModel = initViewModel()
        binding = initBinding(inflater, container)
        loadingDialog = context?.let { LoadingDialog(it) }
        initEvent()
        initData()
        return binding.root
    }

    protected abstract fun initBinding(inflater: LayoutInflater, container: ViewGroup?): T

    protected abstract fun initViewModel(): VM

    @SuppressLint("ShowToast")
    open fun showToast(msg: String?) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
    }

    open fun showLoading(msg: String?) {
        loadingDialog?.let {
            if (it.isShowing) {
                return
            }
            msg?.let {result->
                it.setMessage(result)
            }
            it.setCancelable(false)
            it.setCanceledOnTouchOutside(false)
            it.show()
        }
    }

    open fun showLoading() {
        showLoading(null)
    }

    open fun hideLoading() {
        loadingDialog?.let {
            if (it.isShowing) {
                it.dismiss()
            }
        }
    }

    protected abstract fun initEvent()

    protected abstract fun initData()

    override fun onDestroyView() {
        loadingDialog?.dismiss()
        loadingDialog = null
        super.onDestroyView()
    }
}